package com.controller;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.model.HeadImage;
import com.model.UploadImage;
import com.mortennobel.imagescaling.ResampleOp;
import com.mortennobel.imagescaling.AdvancedResizeOp;
import com.service.ImageStoreService;
import com.util.ImageUtils;

@Controller
@RequestMapping("/")
public class ImageController {

	@Autowired
	private ImageStoreService imageStoreService;

	// /upload/images/2013/10_24/20131024223107.jpg  //
	@RequestMapping(value = "/images/{year}/{day}/{name}", method = RequestMethod.GET)
	public void readImage( HttpServletResponse response, HttpServletRequest request, HttpSession session) {
		
		String pathinfo = request.getPathInfo();
		String fileExt = pathinfo.substring(pathinfo.lastIndexOf(".") + 1);
		String path = pathinfo.substring(0,pathinfo.lastIndexOf("."));
		try {
			path = "/upload"+path;

			UploadImage img = imageStoreService.readUploadImage(path);
			if(img!=null){
				String type = fileExt;
				if (fileExt.equals("jpg")) {
					type = "jpeg";
				}
				response.setContentType("image/" + type);
				response.getOutputStream().write(img.getImage());
			}else{		
				response.setContentType("image/jpeg");
				String path404 = session.getServletContext().getRealPath("/")+"/img/image404.jpg";
				response.getOutputStream().write(ImageUtils.getBytes(path404));
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@RequestMapping(value = "/tmp/{name}", method = RequestMethod.GET)
	public void readTmp( HttpServletResponse response, HttpServletRequest request, HttpSession session) {
		String pathinfo = request.getPathInfo();
		String fileExt = pathinfo.substring(pathinfo.lastIndexOf(".") + 1);
		String path = pathinfo.substring(0,pathinfo.lastIndexOf("."));
		try {
			path = "/upload"+path;

			HeadImage img = imageStoreService.readHeadImage(path);
			if(img!=null){
				String type = fileExt;
				if (fileExt.equals("jpg")) {
					type = "jpeg";
				}
				response.setContentType("image/" + type);
				response.getOutputStream().write(img.getImage());
			}else{		
				response.setContentType("image/jpeg");
				String path404 = session.getServletContext().getRealPath("/")+"/img/image404.jpg";
				response.getOutputStream().write(ImageUtils.getBytes(path404));
			}
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@RequestMapping(value = "/head/{uid}", method = RequestMethod.GET)
	public void readHead( HttpServletResponse response, HttpServletRequest request, HttpSession session,
			@PathVariable("uid") String uid,
			@RequestParam(value = "s", required = false) Integer size) {
		String pathinfo = request.getPathInfo();
		String fileExt = pathinfo.substring(pathinfo.lastIndexOf(".") + 1);
		String path = pathinfo.substring(0,pathinfo.lastIndexOf("."));
		try {
			path = "/upload"+path;
			Image img = null;
			HeadImage headImg = imageStoreService.readHeadImage(path);
			
			//选择并读取图片
			if(uid.equals("anony")){//匿名图片
				img = ImageIO.read(new File(session.getServletContext().getRealPath("/")+"/head/anonymous.jpg"));
			}else if(uid.equals("default")){
				img = ImageIO.read(new File(session.getServletContext().getRealPath("/")+"/head/default.jpg"));
			}else{
				if(headImg!=null){
					ByteArrayInputStream in = new ByteArrayInputStream(headImg.getImage());
					img = ImageIO.read(in);
				}else{
					img = ImageIO.read(new File(session.getServletContext().getRealPath("/")+"/head/default.jpg"));
				}
			}
			
			//根据大小裁剪图片		
			BufferedImage bImage = new BufferedImage(img.getWidth(null), img
					.getHeight(null), BufferedImage.TYPE_INT_BGR);
			Graphics bg = bImage.getGraphics();
			bg.drawImage(img.getScaledInstance(img.getWidth(null), img.getHeight(null),
					Image.SCALE_SMOOTH), 0, 0, null);
			bg.dispose();
			
			//原始大小 直接返回
			if(size==null || size==160){
				ByteArrayOutputStream out = new ByteArrayOutputStream();
		        ImageIO.write(bImage, "JPEG", out);
		        byte[] b = out.toByteArray();
				response.setContentType("image/jpeg");
				response.getOutputStream().write(b);
			}else{
			//缩小后返回
				ResampleOp resampleOp = new ResampleOp(size,size);
				resampleOp.setUnsharpenMask(AdvancedResizeOp.UnsharpenMask.Normal);
				BufferedImage target = resampleOp.filter(bImage, null);			
				
				ByteArrayOutputStream out = new ByteArrayOutputStream();
				
		        ImageIO.write(target, "JPEG", out);
		        byte[] b = out.toByteArray();
				response.setContentType("image/jpeg");
				response.getOutputStream().write(b);
			}
			return;
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return;
	}
}
